import os
from PIL import Image
import piexif

# 定义一个函数来遍历文件夹
def resize_images(directory, max_size_mb=4):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg')):  # 只处理图片文件
                file_path = os.path.join(root, file)
                file_size = os.path.getsize(file_path) / (1024 * 1024)  # 文件大小转换为MB
                if file_size > max_size_mb:
                    # 载入图片
                    with Image.open(file_path) as img:
                        # 读取EXIF信息
                        exif_dict = piexif.load(img.info['exif'])
                        # 调整图片大小
                        while file_size > max_size_mb:
                            new_width = int(img.width / 1.5)
                            new_height = int(img.height / 1.5)
                            img = img.resize((new_width, new_height), Image.LANCZOS)
                            # 重新计算文件大小
                            file_size = img.width * img.height * img.info['bitdepth'] / (1024 * 1024)
                        # 保存EXIF信息
                        exif_bytes = piexif.dump(exif_dict)
                        img.save(file_path, 'JPEG', exif=exif_bytes)
                    print(f"Resized and saved:{file_path}"   " {file}")

# 调用函数，替换为你的目录
resize_images('pic')
